import openpyxl
import os
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed

def modify_excel(input_file, new_value, index):
    """修改 Excel 文件的 I 列数据"""
    try:
        workbook = openpyxl.load_workbook(input_file)
        sheet = workbook.active

        row_index = 7  # 从第 7 行开始
        while True:
            cell = sheet[f'I{row_index}']
            if cell.value is None:  # 如果 I 列单元格为空，则停止
                break
            cell.value = new_value  # 修改 I 列的值
            row_index += 1

        workbook.save(input_file)
        print(f"✅ [文件 {index}] 成功修改: {os.path.basename(input_file)}")
        return True
    except Exception as e:
        print(f"❌ [文件 {index}] 修改失败: {os.path.basename(input_file)} - 错误: {e}")
        return False

def modify_all_excel_files_in_directory(directory, new_value, max_workers=5):
    """并发修改 Excel 目录下的所有文件，并打印修改统计"""
    found_files = [f for f in os.listdir(directory) if f.endswith(".xlsx")]

    if not found_files:
        print("⚠️ 当前目录下没有找到 .xlsx 文件！")
        return

    total_files = len(found_files)
    print(f"📂 发现 {total_files} 个 .xlsx 文件，开始修改...\n")

    success_count = 0
    fail_count = 0

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_file = {
            executor.submit(modify_excel, os.path.join(directory, file), new_value, i + 1): file
            for i, file in enumerate(found_files)
        }

        for future in as_completed(future_to_file):
            file_name = future_to_file[future]
            file_index = found_files.index(file_name) + 1  # 获取当前文件的索引
            if future.result():
                success_count += 1
            else:
                fail_count += 1

    print("\n📊 修改任务完成！")
    print(f"✅ 成功修改: {success_count} 个文件")
    print(f"❌ 失败修改: {fail_count} 个文件")

if __name__ == "__main__":
    if getattr(sys, 'frozen', False):
        script_directory = os.path.dirname(sys.executable)
    else:
        script_directory = os.path.dirname(os.path.abspath(__file__))

    # 切换到 `converted` 文件夹
    converted_directory = os.path.join(script_directory, 'converted')
    
    if not os.path.exists(converted_directory):
        print("⚠️ 没有找到 'converted' 文件夹！")
        sys.exit(1)

    while True:  # 🌀 **添加循环，允许多次输入**
        new_value = input("\n🔄 请输入新的数字 (输入 'exit' 退出): ")
        if new_value.lower() == "exit":
            print("👋 退出程序！")
            break  # 结束循环，退出程序

        # 对 `converted` 文件夹中的文件进行修改
        modify_all_excel_files_in_directory(converted_directory, new_value, max_workers=1)
